<template>
  <div class="popup-input">
    <div class="title">{{ title }}</div>
    <div class="value" @click.stop="showFirstBuyPop">
      <span>{{ showValue }}</span
      ><atom-icon name="arrow-right" class="arrow" />
    </div>
    <atom-bottom-sheet
      v-model="isShow"
      style="height: 128vw"
      :title="title"
      get-container="body"
      @confirm="confirm"
      @cancel="hiddenFirstBuyPop"
      :header-btns="[
        { type: 'cancel', text: '取消' },
        { type: 'confirm', text: '确定' },
      ]"
    >
      <atom-picker
        :columns="columns"
        :default-index="defaultIndex"
        item-height="1rem"
        @change="onChange"
        ref="picker"
      />
    </atom-bottom-sheet>
  </div>
</template>

<script>
import '@atom/atom-icons/icons/arrow-right';
export default {
  props: {
    title: {
      type: String,
      default: '',
    },
    options: {
      type: Array,
      default: () => [],
    },
    value: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      isShow: false,
      nowSelectId: 0,
    };
  },
  computed: {
    showValue() {
      return this.options[this.defaultIndex]?.name || '';
    },
    columns() {
      return this.options.map(item => item.name);
    },
    defaultIndex() {
      const defaultIndex = this.options.findIndex(item => item.id === this.value);
      // 防止使用者传入的value不在选项内的数据
      return defaultIndex === -1 ? 0 : defaultIndex;
    },
  },
  methods: {
    showFirstBuyPop() {
      this.$emit('hidden');
      this.isShow = true;
    },
    hiddenFirstBuyPop() {
      this.$emit('show');
      this.isShow = false;
    },
    onChange(instance, value, index) {
      this.nowSelectId = this.options[index].id;
    },
    confirm() {
      this.$refs.picker.confirm();
      this.$emit('input', this.nowSelectId);
      this.hiddenFirstBuyPop();
    },
  },
  watch: {
    value: {
      handler(nval) {
        this.nowSelectId = nval;
      },
      immediate: true,
    },
  },
};
</script>
<style lang="less" scoped>
.popup-input {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  .title {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: var(--text-1);
    line-height: 18px;
    font-weight: 400;
  }
  .value {
    display: flex;
    justify-content: center;
    align-items: center;
    span {
      font-family: PingFangSC-Regular;
      font-size: 14px;
      color: var(--text-2);
      letter-spacing: 0;
      text-align: right;
      line-height: 18px;
      font-weight: 400;
      min-width: 100px;
    }
    .arrow {
      width: 16px;
      height: 16px;
      margin-left: 4px;
      color: var(--text-1);
    }
  }
}
</style>
